#coding=utf-8
import datetime
from google.appengine.ext import webapp
from google.appengine.ext import db
from django.utils import simplejson as json
from models import get_stock, Stock
from utility import DatetimeJSONEncoder

class Stock(webapp.RequestHandler):
    def get(self):
        code = self.request.get('code')
        s = get_stock(code)
        
        j = json.dumps( s.to_dict(), cls=DatetimeJSONEncoder )
        
        self.response.headers['Content-Type'] = 'application/json' 
        self.response.out.write(j)
        
class TS(webapp.RequestHandler):
    def get(self):
        code = self.request.get('code')
        s = get_stock(code)
        j = json.dumps( s.tss_to_dict(), cls=DatetimeJSONEncoder )
        
        self.response.headers['Content-Type'] = 'application/json' 
        self.response.out.write(j)
        
class Today(webapp.RequestHandler):
    def get(self):
        r = {}
        
        today = datetime.date.today()
        
        q = db.GqlQuery('select * from Stock where created_at = :1', today)
        r['code'] = [s.code for s in q]
        
        q = db.GqlQuery('select * from TradableShare where created_at = :1', today)
        codes = [t.s.code for t in q]
        codes = list( set(codes))
        r['ts'] = codes
        
        j = json.dumps(r, cls=DatetimeJSONEncoder )
        self.response.headers['Content-Type'] = 'application/json' 
        self.response.out.write(j)
        
